package com.syl.servlet;

import com.syl.entity.User;
import com.syl.service.UserService;
import com.syl.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * --- 就那样---
 *
 * @author SYL
 * @date 2025/8/1
 * @desc
 */
@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {

        UserService userService =new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //重定向 到其他页面
        resp.sendRedirect("/register.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受请求
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("password = " + password);
        System.out.println("password = " + username);

        //业务层处理
        User login = userService.login(username, password);

        // 方式二（推荐）：一行代码同时设置（更简洁）
         resp.setContentType("text/html;charset=UTF-8");  //设置响应体编码  设置MIME类型和字符集

        //相应
        if (login !=null){
            PrintWriter writer = resp.getWriter();
            //登录认知
            req.getSession().setAttribute("user",login);
            writer.println("<h1>嗨嗨 成功了老铁!</h1>");
            writer.write("<h1>行啊</h1>");
            resp.sendRedirect("admin.html");

        }else {
            PrintWriter writer = resp.getWriter();
            writer.println("<h1>嗨嗨 失败了!</h1>");
            writer.write("<h1>不中亚</h1>");
        }



    }
}
